package com.shanjupay.common.utilbak;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.*;

public class UrlOnlineUtil {


    private static final Logger LOGGER = LoggerFactory.getLogger(UrlOnlineUtil.class);

    private static String remoteInetAddr = "61.187.240.177";//需要连接的IP地址 111.22.37.11

    //传递服务器IP，通则返回为true,不通返回false
    public static boolean validateIp(String remoteInetIp) {
        boolean reachable = false;
        try {
            InetAddress address = InetAddress.getByName(remoteInetIp);
            reachable = address.isReachable(5000);
        } catch (Exception e) {
            LOGGER.error("IP连接拒绝,URL地址不通", e);
        }
        return reachable;
    }

    public static boolean validateIpAndPort(String remoteInetIp,Integer port) {
        boolean reachable = false;
        try {
            try (Socket soc = new Socket()) {
                soc.connect(new InetSocketAddress(remoteInetIp, port), 5000);
            }
            reachable = true;
        } catch (Exception e) {
            LOGGER.error("IP连接拒绝,URL地址不通", e);
        }
        return reachable;
    }



    public static boolean validateUrl(String romoteUrl) {
        boolean reachable = false;
        try {
            URL url = new URL(romoteUrl);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setConnectTimeout(3000);
            urlCon.setReadTimeout(3000);
            InputStream in = url.openStream();//打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream
            reachable = true;
            LOGGER.info("URL连接正常");
        } catch (Exception e) {
            LOGGER.error("URL连接拒绝,URL地址不通");
        }
        return reachable;
    }


    public static void main(String[] args) {

//        LOGGER.info("**ip地址是否正常***" + validateIpAndPort(remoteInetAddr,50001));
        LOGGER.info("**url地址是否正常***" + validateUrl("http://res-k12.weds.com.cn/101412/20210810/094118_689336625.jpg"));


    }


}
